<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 处理游戏删除请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $gameId = (int)$_GET['delete'];
    
    // 检查游戏是否存在
    $game = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "games WHERE id = ?", [$gameId]);
    
    if ($game) {
        // 删除与游戏相关的记录
        $db->execute("DELETE FROM " . DB_PREFIX . "user_achievements WHERE game_id = ?", [$gameId]);
        $db->execute("DELETE FROM " . DB_PREFIX . "game_records WHERE game_id = ?", [$gameId]);
        $db->execute("DELETE FROM " . DB_PREFIX . "games WHERE id = ?", [$gameId]);
        
        // 删除游戏图片（如果存在）
        if (!empty($game['image']) && file_exists('../' . $game['image'])) {
            @unlink('../' . $game['image']);
        }
        
        $_SESSION['flash_message'] = '游戏已成功删除';
        $_SESSION['flash_type'] = 'success';
    } else {
        $_SESSION['flash_message'] = '游戏不存在';
        $_SESSION['flash_type'] = 'danger';
    }
    
    // 重定向以防止重复提交
    header('Location: games.php');
    exit;
}

// 处理游戏状态修改请求
if (isset($_GET['status']) && is_numeric($_GET['game_id'])) {
    $gameId = (int)$_GET['game_id'];
    $status = $_GET['status'] === 'active' ? 'active' : 'inactive';
    
    // 更新游戏状态
    $db->update('games', ['status' => $status], 'id = ?', [$gameId]);
    
    $_SESSION['flash_message'] = '游戏状态已更新';
    $_SESSION['flash_type'] = 'success';
    
    // 重定向以防止重复提交
    header('Location: games.php');
    exit;
}

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// 搜索功能
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category = isset($_GET['category']) ? trim($_GET['category']) : '';
$status = isset($_GET['status_filter']) ? trim($_GET['status_filter']) : '';

$searchCondition = '';
$searchParams = [];

if (!empty($search) || !empty($category) || !empty($status)) {
    $conditions = [];
    
    if (!empty($search)) {
        $conditions[] = "(name LIKE ? OR description LIKE ?)";
        $searchParams[] = "%$search%";
        $searchParams[] = "%$search%";
    }
    
    if (!empty($category)) {
        $conditions[] = "category = ?";
        $searchParams[] = $category;
    }
    
    if (!empty($status)) {
        $conditions[] = "status = ?";
        $searchParams[] = $status;
    }
    
    $searchCondition = " WHERE " . implode(' AND ', $conditions);
}

// 获取游戏总数
$totalGames = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "games" . $searchCondition, 
    $searchParams
);

// 获取游戏列表
$games = $db->fetchAll(
    "SELECT * FROM " . DB_PREFIX . "games" . $searchCondition . " ORDER BY id DESC LIMIT ?, ?", 
    array_merge($searchParams, [$offset, $perPage])
);

// 获取所有游戏分类
$categories = $db->fetchColumn(
    "SELECT DISTINCT category FROM " . DB_PREFIX . "games ORDER BY category",
    [],
    true // 获取所有结果
);

// 计算总页数
$totalPages = ceil($totalGames / $perPage);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-controller"></i> 游戏管理</h1>
    <a href="game_edit.php" class="btn btn-primary">
        <i class="bi bi-plus-circle"></i> 添加游戏
    </a>
</div>

<!-- 搜索框 -->
<div class="card mb-4">
    <div class="card-body">
        <form action="games.php" method="get" class="row g-3">
            <div class="col-md-4">
                <div class="input-group">
                    <input type="text" class="form-control" id="search" name="search" 
                           placeholder="搜索游戏名称或描述" value="<?php echo htmlspecialchars($search); ?>">
                    <button class="btn btn-primary" type="submit">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                </div>
            </div>
            
            <div class="col-md-3">
                <select class="form-select" id="category" name="category">
                    <option value="">全部分类</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo $category == $cat ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-3">
                <select class="form-select" id="status_filter" name="status_filter">
                    <option value="">全部状态</option>
                    <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>活跃</option>
                    <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>禁用</option>
                </select>
            </div>
            
            <div class="col-md-2">
                <?php if (!empty($search) || !empty($category) || !empty($status)): ?>
                    <a href="games.php" class="btn btn-outline-secondary w-100">清除筛选</a>
                <?php else: ?>
                    <button type="submit" class="btn btn-outline-primary w-100">应用筛选</button>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- 游戏列表 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-table me-1"></i> 游戏列表
        <span class="badge bg-info ms-2"><?php echo $totalGames; ?> 个游戏</span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th width="60">ID</th>
                        <th width="80">图片</th>
                        <th>名称</th>
                        <th>分类</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>玩家数</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($games)): ?>
                        <?php foreach ($games as $game): ?>
                        <tr>
                            <td><?php echo $game['id']; ?></td>
                            <td class="text-center">
                                <?php if (!empty($game['image'])): ?>
                                    <img src="<?php echo htmlspecialchars($game['image']); ?>" alt="游戏图片" class="img-thumbnail" style="max-width: 60px; max-height: 60px;">
                                <?php else: ?>
                                    <i class="bi bi-controller fs-3"></i>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="game_detail.php?id=<?php echo $game['id']; ?>">
                                    <?php echo htmlspecialchars($game['name']); ?>
                                </a>
                                <div class="small text-muted">
                                    <?php echo substr(htmlspecialchars($game['description']), 0, 50) . (strlen($game['description']) > 50 ? '...' : ''); ?>
                                </div>
                            </td>
                            <td><?php echo htmlspecialchars($game['category']); ?></td>
                            <td>
                                <?php if ($game['status'] == 'active'): ?>
                                    <span class="badge bg-success">活跃</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">禁用</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($game['created_at'])); ?></td>
                            <td>
                                <?php
                                // 获取游戏的玩家数量
                                $playersCount = $db->fetchColumn(
                                    "SELECT COUNT(DISTINCT user_id) FROM " . DB_PREFIX . "game_records WHERE game_id = ?",
                                    [$game['id']]
                                );
                                echo number_format($playersCount);
                                ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="game_detail.php?id=<?php echo $game['id']; ?>" class="btn btn-info" title="查看详情">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <a href="game_edit.php?id=<?php echo $game['id']; ?>" class="btn btn-primary" title="编辑">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="game_resources.php?game_id=<?php echo $game['id']; ?>" class="btn btn-success" title="管理资源">
                                        <i class="bi bi-archive"></i>
                                    </a>
                                    <a href="game_preview.php?id=<?php echo $game['id']; ?>" class="btn btn-warning" title="游戏预览">
                                        <i class="bi bi-controller"></i>
                                    </a>
                                    <?php if ($game['status'] == 'active'): ?>
                                        <a href="games.php?game_id=<?php echo $game['id']; ?>&status=inactive" 
                                           class="btn btn-secondary" title="禁用"
                                           onclick="return confirm('确定要禁用此游戏吗？')">
                                            <i class="bi bi-slash-circle"></i>
                                        </a>
                                    <?php else: ?>
                                        <a href="games.php?game_id=<?php echo $game['id']; ?>&status=active" 
                                           class="btn btn-success" title="激活">
                                            <i class="bi bi-check-circle"></i>
                                        </a>
                                    <?php endif; ?>
                                    <a href="games.php?delete=<?php echo $game['id']; ?>" 
                                       class="btn btn-danger" title="删除"
                                       onclick="return confirm('确定要删除此游戏吗？此操作不可撤销，与游戏相关的所有数据将被删除。')">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="text-center">没有找到符合条件的游戏</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 分页 -->
    <?php if ($totalPages > 1): ?>
    <div class="card-footer">
        <nav>
            <ul class="pagination justify-content-center mb-0">
                <?php
                // 分页导航
                renderPagination($page, $totalPages, 'games.php', [
                    'search' => $search,
                    'category' => $category,
                    'status_filter' => $status
                ]);
                ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<?php
require_once 'includes/footer.php';
?> 